package com.piece.blog.controller;

import com.piece.blog.dto.TrainingQuestionDTO;
import com.piece.blog.model.TrainingQuestion;
import com.piece.blog.service.TrainingQuestionItemService;
import com.piece.blog.service.TrainingQuestionService;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.collection.MapUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.controller.FrameWorkController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 试卷题目Controller
 *
 * @author onepiece
 * @date 2023-09-12
 */
@RestController
@Api(tags = {"试卷题目管理"})
@RequestMapping("/api/training/exam/question")
public class TrainingQuestionController extends FrameWorkController {

    @Resource
    private TrainingQuestionService trainingQuestionService;
    @Resource
    private TrainingQuestionItemService trainingQuestionItemService;

    @PostMapping("/list")
    @AclPermission(code = "training:question:view")
    @ApiOperation(value = "查询题库题目列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = trainingQuestionService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "training:question:view")
    @ApiOperation(value = "查询题库题目分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = trainingQuestionService.findPage(queryTable);
        List<TrainingQuestion> tableData = dataTable.getData();
        if (tableData.size() > 0) {
            tableData = tableData.stream().map(question -> {
                question.setAnswer(null);
                question.setAnalysis(null);
                return question;
            }).collect(Collectors.toList());
        }
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "training:question:view")
    @ApiOperation(value = "加载题库题目表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        Long id = Convert.toLong(getRequest().getParameter("id"), null);
        boolean reSort = Convert.toBool(getRequest().getParameter("resort"), false);
        TrainingQuestionDTO question = trainingQuestionService.loadByQuestionId(id, reSort);
        return success(question);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "training:question:edit")
    @ApiOperation(value = "保存题库题目表单数据")
    @ApiImplicitParam(value = "题库题目数据", dataTypeClass = TrainingQuestionDTO.class, type = "body")
    public AjaxResponse save(@RequestBody TrainingQuestionDTO questionInfo) {
        try {
            Long id = Convert.toLong(getRequest().getParameter("id"));
            trainingQuestionService.insertOrUpdate(questionInfo);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "training:question:delete")
    @ApiOperation(value = "删除题库题目数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable Long id) throws Exception {
        trainingQuestionService.delete(id);
        trainingQuestionItemService.deleteByQuestion(id);
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "training:question:delete")
    @ApiOperation(value = "删除题库题目数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            trainingQuestionService.delete(Convert.toLongArray(ids));
            trainingQuestionItemService.deleteByQuestion(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @GetMapping("/preview/{id}")
    @ApiOperation(value = "加载题库题目表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse preview(@PathVariable Long id) {
        boolean reSort = Convert.toBool(getRequest().getParameter("resort"), false);
        TrainingQuestionDTO question = trainingQuestionService.loadByQuestionId(id, reSort);
        question.setAnswer(null);
        question.setAnalysis(null);
        return success(question);
    }

    @PostMapping("/answer/{id}")
    @ApiOperation(value = "获取题目答案")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse answer(@PathVariable Long id) {
        TrainingQuestion question = trainingQuestionService.findById(id);
        if (null != question) {
            List answers = new ArrayList();
            // 多选题、填空题重新赋值
            if ("1".equals(question.getType()) || "3".equals(question.getType())) {
                answers.addAll(Arrays.asList(question.getAnswer().split("\\{:\\}")));
            } else {
                answers.add(question.getAnswer());
            }
            Map<String, Object> response = MapUtil.builder(new HashMap<String, Object>())
                    .put("answer", answers)
                    .put("analysis", question.getAnalysis())
                    .build();
            return success(response);
        } else {
            return error(I18nUtil.message(ExceptionConstants.NOT_EXIST, "试题"));
        }
    }
}
